<?php
// +----------------------------------------------------------------------
// | Tplay [ WE ONLY DO WHAT IS NECESSARY ]
// +----------------------------------------------------------------------
// | Copyright (c) 2017 http://tplay.pengyichen.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 听雨 < 389625819@qq.com >
// +----------------------------------------------------------------------


namespace app\admin\controller;
use think\Db;
use \think\Cookie;
use app\admin\model\Tag as TagModel;

class Taglable extends User
{
    /**
     * TAG列表
     */
    public function index()
    {
        $model = new TagModel();
        $post = $this->request->post();
        //分页bug处理
        $temp_page=request()->param('page');
        if(isset($temp_page)){
            //条件从缓存取出
            $post=Cookie::get('postlist');
        }else{
            //把条件写入缓存
            Cookie::set('postlist',$post);
        }
        $where='';
        if (isset($post['keywords']) and !empty($post['keywords'])) {
            $where['tag_name'] = ['like', '%' . $post['keywords'] . '%'];
        }

        if (isset($post['tag_type']) and $post['tag_type'] > 0) {
            $where['tag_type'] = $post['tag_type'];
        }

        if (isset($post['tag_status']) and $post['tag_status'] > 0) {
            $where['tag_status'] = $post['tag_status'];
        }

        $typeData = db("tag_type")->select();
        $typeName = [];
        foreach ($typeData as $k=>$v) {
            $typeName[$v['id']] = $v['name'];
        }
        $info = $model->where($where)->order('creattime desc')->paginate(20);
        foreach ($info as $k=>$v) {
            $info[$k]['tag_type_name'] = $typeName[$v['tag_type']];
        }

        $this->assign('info', $info);
        $this->assign('typeData', $typeData);
        $this->assign('wherelist', $post);
        return $this->fetch();
    }

    /**
     * 新增、修改TAG
     */
    public function addtag()
    {
        $model = new TagModel();
        $id = $this->request->has('id') ? $this->request->param('id', 0, 'intval') : 0;
        if ($id > 0) {
            //是修改操作
            if ($this->request->isPost()) {
                //是提交操作
                $post = $this->request->post();
                //验证  唯一规则： 表名，字段名，排除主键值，主键名
                $validate = new \think\Validate([
                    ['tag_name', 'require', 'TAG名称不能为空'],
                ]);
                //验证部分数据合法性
                if (!$validate->check($post)) {
                    $this->error('提交失败：' . $validate->getError());
                }

                $basetagname =Db::name('tag')->where('tag_id', $id)->field('tag_name,tag_type')->find();

                if($basetagname['tag_name']!=$post['tag_name']||$basetagname['tag_type']!=$post['tag_type']){
                    //验证昵称是否存在
                    $where['tag_name']=$post['tag_name'];
                    $where['tag_type']=$post['tag_type'];
                    $nickname = db("tag")->where($where)->select();
                    if (!empty($nickname)) {
                        return $this->error('提交失败：该TAG名称已被占用');
                    }
                }

                $post['updatetime']=time();
                if (false == $model->allowField(true)->save($post, ['tag_id' => $id])) {
                    return $this->error('修改失败');
                } else {
                    return $this->success('修改成功');
                }
            } else {
                //非提交操作
                $tagType = db("tag_type")->select();
                $this->assign('tagType', $tagType);
                $info = $model->where('tag_id', $id)->find();
                $this->assign('info', $info);
                return $this->fetch();
            }
        } else {
            //是新增操作
            if ($this->request->isPost()) {
                //是提交操作
                $post = $this->request->post();
                //验证  唯一规则： 表名，字段名，排除主键值，主键名
                $validate = new \think\Validate([
                    ['tag_name', 'require', 'TAG名称不能为空'],
                ]);
                //验证部分数据合法性
                if (!$validate->check($post)) {
                    $this->error('提交失败：' . $validate->getError());
                }

                $where['tag_name']=$post['tag_name'];
                $where['tag_type']=$post['tag_type'];
                //验证昵称是否存在
                $tagname = db("tag")->where($where)->select();
                if (!empty($tagname)) {
                    return $this->error('提交失败：该TAG名称已被占用');
                }

                $post['creattime']=time();
                $post['updatetime']=time();
                if (false == $model->allowField(true)->save($post)) {
                    return $this->error('添加TAG失败');
                } else {
                    return $this->success('添加TAG成功','',['id'=>$model->tag_id,'name'=>$post['tag_name']]);
                }
            } else {
                //非提交操作
                $tagType = db("tag_type")->select();
                $this->assign('tagType', $tagType);
                return $this->fetch();
            }
        }
    }

    /**
     * 禁用/启用tag
     */
    public function delete()
    {
        if($this->request->isAjax()) {
            $model = new TagModel();
            $id = $this->request->has('id') ? $this->request->param('id', 0, 'intval') : 0;
            $status = $this->request->has('status') ? $this->request->param('status', 0, 'intval') : 0;
            if($status){
                $data['tag_status'] =$status;
            }
            if($status==2){
                $msg='禁用';
            }else{
                $msg='启用';
            }
            $data['updatetime']=time();
            if (false == $model->allowField(true)->save($data, ['tag_id' => $id])) {
                return $this->error($msg.'失败');
            } else {
                return $this->success($msg.'TAG成功', 'admin/taglable/index');
            }
        }
    }

    //真实删除
    public function realDelete()
    {
        if($this->request->isAjax()) {
            $model = new TagModel();
            $id = $this->request->has('id') ? $this->request->param('id', 0, 'intval') : 0;
            if (false == $model->where("tag_id",$id)->delete()) {
                return $this->error('删除失败');
            } else {
                return $this->success('删除TAG成功');
            }
        }
    }

    //TAG类型列表
    public function typeIndex()
    {
        $info = db("tag_type")->select();
        $this->assign('info', $info);
        return $this->fetch();
    }

    //新增类型
    public function addType()
    {
        $id = $this->request->has('id') ? $this->request->param('id', 0, 'intval') : 0;
        if ($id > 0) {
            //是修改操作
            if ($this->request->isPost()) {
                //是提交操作
                $post = $this->request->post();
                $where['name'] = $post['name'];
                $where['id'] = ['NEQ',$id];
                $tag_type = db("tag_type")->where($where)->find();
                if(!empty($tag_type)){
                    return $this->error('该名称已存在');
                }

                if (false == db("tag_type")->where("id",$id)->update(['name'=>$post['name']])) {
                    return $this->error('修改失败');
                } else {
                    return $this->success('修改成功');
                }
            } else {
                //非提交操作
                $info = db("tag_type")->where('id', $id)->find();
                $this->assign('info', $info);
                return $this->fetch();
            }
        } else {
            //是新增操作
            if ($this->request->isPost()) {
                //是提交操作
                $post = $this->request->post();
                $where['name'] = $post['name'];
                $where['id'] = ['NEQ',$id];
                $tag_type = db("tag_type")->where($where)->find();
                if(!empty($tag_type)){
                    return $this->error('该名称已存在');
                }

                if (false == db("tag_type")->insert(['name'=>$post['name']])) {
                    return $this->error('新增失败');
                } else {
                    return $this->success('新增成功');
                }
            } else {
                //非提交操作
                return $this->fetch();
            }
        }
    }

    //删除类型
    public function deleteType()
    {
        if($this->request->isAjax()) {
            $id = $this->request->has('id') ? $this->request->param('id', 0, 'intval') : 0;
            $tagData = db("tag")->where("tag_type",$id)->select();
            if(!empty($tagData)){
                return $this->error('不能删除已存在标签的类型');
            }

            if (false == db("tag_type")->where("id",$id)->delete()) {
                return $this->error('删除失败');
            } else {
                return $this->success('删除成功');
            }
        }
    }

    //接口新增TAG
    public function ajaxAddTag()
    {
        $post = $this->request->post();
        //验证  唯一规则： 表名，字段名，排除主键值，主键名
        $validate = new \think\Validate([
            ['tag_name', 'require', 'TAG名称不能为空'],
        ]);
        //验证部分数据合法性
        if (!$validate->check($post)) {
            $this->error('提交失败：' . $validate->getError());
        }

        $where['tag_name']=$post['tag_name'];
        $where['tag_type']=$post['tag_type'];
        //验证昵称是否存在
        $tagname = db("tag")->where($where)->select();
        if (!empty($tagname)) {
            return $this->error('提交失败：该TAG名称已被占用');
        }

        $post['creattime']=time();
        $post['updatetime']=time();
        $post['tag_status']=1;
        $model = new TagModel();
        if (false == $model->allowField(true)->save($post)) {
            return $this->error('添加标签成功');
        } else {
            $data = $model->where(['tag_status'=>1,'tag_type'=>$post['tag_type']])->field("tag_id as id,tag_name as name")->select();
            $id = db()->getLastInsID();
            return $this->success("添加标签成功",'',['list'=>$data,'curTagId'=>$id]);
        }
    }

    public function changeShowStatus()
    {
        $post = request()->post();
        $id = $post['id']??0;

        $tag = db('tag')->find($id);
        if(empty($id) || empty($tag)) return $this->error('标签有误');
        foreach ($post as $key=>$value){
            if(!in_array($key,['tob_show','toc_show'])){
                unset($post[$key]);
            }
        }
        if(empty($post)) return $this->error('修改失败');
        $res = db('tag')->where('tag_id',$id)->update($post);
        if($res!==false){
            return $this->success('修改成功');
        }else{
            return $this->error('修改失败');
        }
    }

}
